package org.odst.util;

import java.util.List;
import java.util.Map;

import org.odftoolkit.odfdom.doc.table.OdfTable;
import org.odftoolkit.odfdom.doc.table.OdfTableCell;
import org.odst.formula.Formula;
import org.odst.formula.ListRange;


/**
 * @author Leonid Vysochyn
 * @author Cyril PODER
 */
public class FormulaUtil {

    /**
     * This method updates formula cells
     *
     * @param sheet            Sheet to update
     * @param ignoreUnresolved Flag indicating should unresolved formulas be removed or just ignored
     */
    public static void updateFormulas(OdfTable sheet, List<Formula> formulas, Map<String, ListRange> listRanges, Map<String, org.odst.parser.Cell> namedCells, boolean ignoreUnresolved) {
        for (int i = 0; i < formulas.size(); i++) {
            Formula formula = (Formula) formulas.get(i);
            String formulaString = formula.getAppliedFormula( listRanges, namedCells );
			try {
				OdfTableCell hssfCell = sheet.getCellByPosition(formula.getCellNum(), formula.getRowNum());
	            if (formulaString != null) {
	                hssfCell.setFormula(formulaString);
	            } else {
	                if (!ignoreUnresolved) {
	                	hssfCell.setStringValue("");
	                    formulas.remove(i--);
	                }
	            }
			} catch (IndexOutOfBoundsException e) {
				e.printStackTrace();
			}
        }
    }

    /**
     * @param formulas {@link List} of {@link Formula} objects
     * @param formula {@link Formula} object to check
     * @return true if given {@link Formula} already exists in formulas list
     */
    static boolean formulaExists(List<Formula> formulas, Formula formula) {
        for (Formula cur : formulas) {
            if (cur.getFormula().equals(formula.getFormula())) {
                return true;
            }
        }
        return false;
    }


}
